package com.ksyun.onepass.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ksyun.onepass.domain.common.TradeResponse;
import com.ksyun.onepass.domain.common.UserTradeRequest;
import com.ksyun.onepass.service.TradeService;
import lombok.RequiredArgsConstructor;
import org.springframework.cache.CacheManager;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.annotation.PreDestroy;
import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@RestController
@RequestMapping("/onePass")
@RequiredArgsConstructor
public class TradeController {
    @Resource
    private CacheManager cacheManager;
    private final TradeService tradeService;

    // 创建一个固定线程池
    private final ExecutorService executorService = Executors.newFixedThreadPool(100);
    private final ObjectMapper objectMapper = new ObjectMapper();

    @PostMapping("/userTrade")
    public ResponseEntity<String> userTrade(
            @RequestHeader(value = "X-KSY-REQUEST-ID") String requestId,
            @RequestBody UserTradeRequest request) throws JsonProcessingException {

        // 判断请求ID是否已存在，确保幂等性
        if (cacheManager.getCache("TradeCache").get(requestId) != null) {
            // 如果存在重复请求，返回响应
            return ResponseEntity.ok(createSuccessResponse(requestId));
        }

        // 验证金额 (最大值 10000，最小值 0.01)
        if (request.getAmount().compareTo(BigDecimal.ZERO) <= 0 ||
                request.getAmount().compareTo(new BigDecimal(10000)) > 0) {
            return ResponseEntity.badRequest().body("Invalid amount");
        }

        // 使用 CompletableFuture 提交任务到线程池
        CompletableFuture<String> futureResponse = CompletableFuture.supplyAsync(() -> {
            boolean success = tradeService.executeTrade(request.getSourceUid(), request.getTargetUid(), request.getAmount());

            if (success) {
                cacheManager.getCache("TradeCache").put(requestId, true);
                return createSuccessResponse(requestId);
            } else {
                return "{\"error\": \"Trade failed\"}";
            }
        }, executorService); // 提交任务到线程池

        // 等待 CompletableFuture 完成并获取结果
        String responseJson;
        try {
            responseJson = futureResponse.get(); // 等待完成
        } catch (InterruptedException | ExecutionException e) {
            responseJson = "{\"error\": \"Server error\"}";
        }

        return ResponseEntity.ok(responseJson); // 返回最终结果
    }
    private String createSuccessResponse(String requestId) {
        TradeResponse response = new TradeResponse("ok", 200, requestId, null);
        try {
            return objectMapper.writeValueAsString(response);
        } catch (JsonProcessingException e) {
            return "{\"error\": \"Failed to serialize response\"}";
        }
    }

    // 在适当情况下关闭线程池
    @PreDestroy
    public void shutdown() {
        executorService.shutdown(); // 关闭线程池
    }
}
